package com.example.javaproject.datastructure.map;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * Description:
 * <br/>Author:  tianjinyong
 * <br/>Date:    2020/7/3 3:31 PM
 */
public class LinkedHashMaoDemo {

    public static void main(String[] args) {
        testSimpleLru();
    }

    /**
     * 简单实现一个LRU 算法
     */
    public static void testSimpleLru() {
        SimpleLruCache<Integer, Integer> cache = new SimpleLruCache<>(3);

        for(int i = 0; i < 10; i++) {
            cache.save(i, i * i);
        }

        System.out.println("插入10个键值对后，缓存内容：\n" + cache + "\n");


        System.out.println("访问键值为7的节点后，缓存内容：");
        cache.getOne(7);
        System.out.println(cache + "\n");

        System.out.println("插入键值为1的键值对后，缓存内容：");
        cache.save(1, 1);
        System.out.println(cache);
    }

    static class SimpleLruCache<K, V> extends LinkedHashMap<K, V> {
        private static final int MAX_NODE_NUM = 100;

        private int limit;

        public SimpleLruCache() {
            this(MAX_NODE_NUM);
        }

        public SimpleLruCache(int limit) {
            super(limit, 0.75f, true);
            this.limit = limit;
        }

        public V save(K key, V val) {
            return put(key, val);
        }

        public V getOne(K key) {
            return get(key);
        }

        public boolean exists(K key) {
            return containsKey(key);
        }

        /**
         * 节点超过限定时，删除最近最少使用的元素
         *
         * @param eldest
         * @return
         */
        @Override
        protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
            return size() > limit;
        }
    }

}
